package com.adobe.apprise.commands
{
	import com.adobe.apprise.database.DatabaseEvent;
	import com.adobe.apprise.database.DatabaseResponder;
	import com.adobe.apprise.events.SearchEvent;
	import com.adobe.apprise.model.ModelLocator;
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import mx.collections.ArrayCollection;
	import mx.utils.StringUtil;
	
	public class SearchCommand implements ICommand
	{
		public function execute(ce:CairngormEvent):void
		{
			var searchTerm:String = SearchEvent(ce).searchTerm;
			if (searchTerm == null || StringUtil.trim(searchTerm).length == 0)
			{
				ModelLocator.getInstance().posts = null;
				ModelLocator.getInstance().selectedPost = null;
				return;
			}
			var responder:DatabaseResponder = new DatabaseResponder();
			responder.addEventListener(DatabaseEvent.RESULT_EVENT,
				function(e:DatabaseEvent):void
				{
					ModelLocator.getInstance().posts = new ArrayCollection(e.data);
					ModelLocator.getInstance().selectedPost = null;
				});
			
			searchTerm = searchTerm.replace(new RegExp("'","g"),"''");
			var searchTermArray:Array = searchTerm.split(' ');
			//searchTermArray may contain any number of whitespace elements, so we use a new array to hold only terms
			var justSearchTerms:Array = new Array(); 
			
			for ( var i:uint = 0; i < searchTermArray.length; i++ )
			{
				var currentTerm:String = searchTermArray[i];
				if ( currentTerm != '' && currentTerm != ' ' )
				{
					//create a query for this term, and store it in the final search term array
					justSearchTerms[i] = "(posts.content LIKE '%" + currentTerm + "%' OR posts.title LIKE '%" + currentTerm + "%')";
				}
			}
			
			var searchString:String = "";
			for ( i = 0; i < justSearchTerms.length; i++ )
			{
				currentTerm = justSearchTerms[i];
				var nextTerm:String = justSearchTerms[i+1];
				if ( currentTerm != '' )
				{
					searchString += currentTerm;
					//if there's another term after this, add an 'AND' between the two
					if ( nextTerm != null )
					{
						searchString += " AND ";
					}
				}
			}
			
			//if searchCommand has been called and there's no resulting searchString, default to a match for everything
			if ( searchString == "" )
			{
				searchString = "(posts.content LIKE '%')";
			} 	
			//trace(searchString);
			
			//perform the search
			ModelLocator.getInstance().db.searchPosts(responder, searchString);
		}
	}
}
